﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Reminder
{
    [XmlRootAttribute(ElementName = "Locations", IsNullable = false)]
    public class LocationCollection : List<Location> // HashSet<> is not available in .NET CF.
    {
        public void Save(Stream stream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(LocationCollection));
            serializer.Serialize(stream, this);
        }

        public void Save(string file)
        {
            using (FileStream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                Save(stream);
            }
        }

        public static LocationCollection Load(Stream stream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(LocationCollection));
            LocationCollection locations = (LocationCollection)serializer.Deserialize(stream);
            foreach (Location location in locations)
            {
                if (location.loadedParentGuid == Guid.Empty)
                    continue;

                location.Parent = locations.FirstOrDefault(l =>
                    l.Guid == location.loadedParentGuid);
            }
            return locations;
        }

        public static LocationCollection Load(string file)
        {
            using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return Load(stream);
            }
        }
    }
}
